package org.career.pdung.facade;

import org.career.pdung.domain.User;
import org.career.pdung.form.RegistrationForm;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.apache.commons.lang.StringUtils;


public class UserConvester {
	private Md5PasswordEncoder passwordEncoder = new Md5PasswordEncoder();
	public User doConvestFromCustomerFormToUser(RegistrationForm customerForm , User user){
		user.setFirstName(customerForm.getFirstName());
		user.setLastName(customerForm.getLastName());
		user.setEmail(customerForm.getEmail());
		user.setRoles("ROLE_USER");
		user.setPassWord(passwordEncoder.encodePassword(customerForm.getPassword(), null));
		user.setUserType(customerForm.getUserType());
		user.setGender(customerForm.getGender());
		return user;
	}
    public void convertToFormFromFB(RegistrationForm customerForm, JSONObject payloadObject , String facebookID) {
		try {
		    JSONObject registrationJson = payloadObject.getJSONObject("registration");
		    final String name = registrationJson.getString("name");
		    customerForm.setFirstName(StringUtils.defaultIfEmpty(StringUtils.substringBefore(name, " "), name));
		    customerForm.setLastName(StringUtils.defaultIfEmpty(StringUtils.substringAfter(name, " "), ""));	    
		    customerForm.setEmail("");
		    customerForm.setPassword("");
		    customerForm.setFacebookId(facebookID);		
		} catch (JSONException e) {
		    e.printStackTrace();
		}

    }
	
}


